package com.xbongbong.pro.statistic.service.result;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.StageTypeEnum;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.pojo.StageFindPojo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.service.stage.StageFindStrategy;
import com.xbongbong.pro.service.stage.factory.StageFindFactory;
import com.xbongbong.pro.service.toolbox.statistic.help.ChartQueryHelp;
import com.xbongbong.pro.service.toolbox.statistic.util.ChartResultUtil;
import com.xbongbong.pro.statistic.constant.ChartI18Constant;
import com.xbongbong.pro.statistic.enums.NumFormatEnum;
import com.xbongbong.pro.statistic.enums.SystemCodeEnum;
import com.xbongbong.pro.statistic.pojo.TimePojo;
import com.xbongbong.pro.statistic.result.pojo.ChartResultPojo;
import com.xbongbong.pro.statistic.result.pojo.PanoramaPojo;
import com.xbongbong.pro.statistic.result.pojo.vo.ChartResultDetailVO;
import com.xbongbong.pro.statistic.result.pojo.vo.ResultDataTableVO;
import com.xbongbong.pro.statistic.result.pojo.vo.ResultTableVO;
import com.xbongbong.pro.statistic.through.pojo.dto.ThroughDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.PageConstant;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.MarketActivityEnum;
import com.xbongbong.saas.enums.dictionary.ClueStatusEnum;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.CardinalityAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.SumAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.TopHitsAggregationBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author guohui.zhang
 * @Title: 市场活动相关统计
 * @date 2020/12/415:12
 */
@Component
public class MarketActivityResult extends ChartResultParentService implements ChartResultSystem,PanoramaResult  {
    @Resource
    private PaasFormExplainModel paasFormExplainModel;

    @Override
    public Object getTarget(ChartResultPojo chartResultPojo, ChartResultDetailVO chartResultDetailVO) throws XbbException {
        SystemCodeEnum systemCodeEnum = chartResultPojo.getSystemCodeEnum();
        switch (systemCodeEnum){
            // 市场活动ROI
            case MARKET_ACTIVITY_ROI_ACTIVITY:
                return  marketActivityROIChart(chartResultPojo, chartResultDetailVO);
            // 市场活动转化ROI分析
            case MARKET_ACTIVITY_CONVERSION:
                return marketActivityConversion(chartResultPojo, chartResultDetailVO);
            // 活动类型转化分析
            case ACTIITY_CONVERSION_ANAYALSIS:
                return marketConversionAnaylais(chartResultPojo, chartResultDetailVO);
            default:
                break;
        }
        return null;
    }

    /**
     * 活动类型转化分析
     * @param chartResultPojo
     * @param chartResultDetailVO
     * @return
     */
    private Object marketConversionAnaylais(ChartResultPojo chartResultPojo, ChartResultDetailVO chartResultDetailVO) throws XbbException {
        // 查询市场活动活动类型
        PaasFormExplainEntity explainEntity = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.MARKET_ACTIVITY.getCode(), chartResultPojo.getCorpid());
        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(explainEntity.getExplains());
        FieldAttrEntity fieldAttrEntity = explainMap.get(MarketActivityEnum.GENRE.getAttr());
        List<ItemPoJo> items = fieldAttrEntity.getItems();
        Map<Object, String> types = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        items.forEach(item-> types.put(item.getValue(), item.getText()));
        ChartResultUtil.formatPage(chartResultPojo, PageConstant.DEFAULT_PAGE_SIZE_SMALL);
        String fieldTime = "marketEndTime";
        String corpid = chartResultPojo.getCorpid();
        String unit = chartResultPojo.getUnit();
        chartResultPojo.setPageSize(200);
        BoolQueryBuilder boolQueryBuilder  = chartQueryHelp.boolQueryBuilder4Time(chartResultPojo, fieldTime, true);
        Map<Long, String> marketId2Name = new HashMap<>(chartResultPojo.getPageSize());
        PageHelper pageHelper = chartQueryHelp.getMarketId(chartResultPojo, corpid, boolQueryBuilder, marketId2Name);
        String field = "marketType.keyword";
        // 获取数据
        List<List<ResultDataTableVO>> tableData = getTableData2Market(boolQueryBuilder, field, types, chartResultPojo, marketId2Name);
        pageHelper.setRowsCount(tableData.size());
        // 客户数量
        ResultTableVO table = new ResultTableVO();
        List<String> title = Arrays.asList(String.format(I18nMessageUtil.getMessage(ChartI18Constant.MARKET_ACTIVITY_CONVERSION_TITLE), unit, unit).split(","));
        table.setTitle(systemChartHelp.titleNumRight(title));
        table.setMarketData(tableData);
        // table.setPageHelper(pageHelper);
        table.setSystemCode(SystemCodeEnum.ACTIITY_CONVERSION_ANAYALSIS.getSystemCode());
        table.setTableName(SystemCodeEnum.ACTIITY_CONVERSION_ANAYALSIS.getName());
        chartResultDetailVO.setTable(table);
        return chartResultDetailVO;
    }

    /**
     * 市场活动转化分析ROE
     * @param chartResultPojo
     * @param chartResultDetailVO
     * @return
     * modift by yingjf  新增合同订单数 合同订单金额 线索转合同转化率
     */
    private Object marketActivityConversion(ChartResultPojo chartResultPojo, ChartResultDetailVO chartResultDetailVO) throws XbbException {
        ChartResultUtil.formatPage(chartResultPojo, PageConstant.DEFAULT_PAGE_SIZE_SMALL);
        String fieldTime = "marketEndTime";
        String corpid = chartResultPojo.getCorpid();
        String unit = chartResultPojo.getUnit();
        BoolQueryBuilder boolQueryBuilder  = chartQueryHelp.boolQueryBuilder4Time(chartResultPojo, fieldTime, true);
        Map<Long, String> marketId2Name = new HashMap<>(chartResultPojo.getPageSize());
        PageHelper pageHelper = chartQueryHelp.getMarketId(chartResultPojo, corpid, boolQueryBuilder,marketId2Name);
        String field = "marketId";
        TopHitsAggregationBuilder sort = AggregationBuilders.topHits("topHits").sort("marketId", SortOrder.DESC);
        // 列表数据
        List<List<ResultDataTableVO>> tableData = getTableData2Market(boolQueryBuilder, field ,null, chartResultPojo, marketId2Name);
        // 客户数量
        ResultTableVO table = new ResultTableVO();
        List<String> title = Arrays.asList(String.format(I18nMessageUtil.getMessage(ChartI18Constant.MARKET_ACTIVITY_TYPE_CONVERSION_TITLE), unit, unit).split(","));
        table.setTitle(systemChartHelp.titleNumRight(title));
        table.setMarketData(tableData);
        table.setPageHelper(pageHelper);
        table.setSystemCode(SystemCodeEnum.MARKET_ACTIVITY_CONVERSION.getSystemCode());
        table.setTableName(SystemCodeEnum.MARKET_ACTIVITY_CONVERSION.getName());
        chartResultDetailVO.setTable(table);
        return chartResultDetailVO;
    }

    private List<List<ResultDataTableVO>> getTableData2Market(BoolQueryBuilder boolQueryBuilder, String field, Map<Object, String> types, ChartResultPojo chartResultPojo, Map<Long, String> marketId2Name) throws XbbException {
        TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("aggs01").field(field).order(BucketOrder.key(false));
        TermsAggregationBuilder termsAggregationBuilder2 = AggregationBuilders.terms("aggs011").field("clueStatus.keyword");
        CardinalityAggregationBuilder clueIdCardina = AggregationBuilders.cardinality("deviceCard").field("clueId").precisionThreshold(1000);
        termsAggregationBuilder2.subAggregation(clueIdCardina).size(Integer.MAX_VALUE);
        termsAggregationBuilder.subAggregation(termsAggregationBuilder2);

        // 统计客户数目
        TermsAggregationBuilder termsAggregationBuilder3 = AggregationBuilders.terms("aggs012").field("customerId");
        CardinalityAggregationBuilder customerIdCardinality = AggregationBuilders.cardinality("deviceCard").field("customerId").precisionThreshold(1000);
        termsAggregationBuilder3.subAggregation(customerIdCardinality).size(Integer.MAX_VALUE);
        termsAggregationBuilder.subAggregation(termsAggregationBuilder3);
        // 统计机会数量
        TermsAggregationBuilder termsAggregationBuilder1 = AggregationBuilders.terms("aggs013").field("saleStage.keyword");
        CardinalityAggregationBuilder saleOpportunityIdCardinality = AggregationBuilders.cardinality("deviceCard").field("saleOpportunityId").precisionThreshold(1000);
        termsAggregationBuilder1.subAggregation(saleOpportunityIdCardinality);
        termsAggregationBuilder1.subAggregation(new SumAggregationBuilder("saleMoney").field("saleMoney")).size(Integer.MAX_VALUE);
        termsAggregationBuilder.subAggregation(termsAggregationBuilder1);

        // 统计合同数量
        TermsAggregationBuilder termsAggregationBuilder4 = AggregationBuilders.terms("aggs014").field("contractId");
        CardinalityAggregationBuilder contractIdCardinality = AggregationBuilders.cardinality("deviceCard").field("contractId").precisionThreshold(1000);
        termsAggregationBuilder4.subAggregation(contractIdCardinality);
        termsAggregationBuilder4.subAggregation(new SumAggregationBuilder("contractMoney").field("contractMoney")).size(Integer.MAX_VALUE);
        termsAggregationBuilder.subAggregation(termsAggregationBuilder4);

        termsAggregationBuilder.size(Integer.MAX_VALUE);
        JSONObject resultJsonObject = esHelper.elasticAggs4Buckets2Object(IndexTypeEnum.IDX_STATICS_MARKET_DATA, boolQueryBuilder, termsAggregationBuilder);
        JSONArray bucketsArray = resultJsonObject.getJSONArray("buckets");
        // 获取所有的成功阶段
        StageFindStrategy stageFindStrategy = StageFindFactory.getStageFindStrategy(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode());
        Set<String> winStatisticsCodeIn = stageFindStrategy.findStageCodeList(chartResultPojo.getCorpid(), new StageFindPojo(StageTypeEnum.getSuccessType()));
        List<List<ResultDataTableVO>> tableData = new ArrayList<>();
        Integer numFormat = chartResultPojo.getNumFormat();
        NumFormatEnum numFormatEnum = NumFormatEnum.getByCode(numFormat);
        for (Object o : bucketsArray) {
            if (o!=null){
                JSONObject json = (JSONObject) o;
                String replaceKey = null;
                String key = null;
                if (Objects.nonNull(types)) {
                    // key = json.getString("key");
                    if (StringUtil.isNotEmpty(json.getString("key"))){
                        if (Objects.nonNull(types.get(json.getString("key")))) {
                            replaceKey = json.getString("key");
                            key = types.get(json.getString("key")).toString();
                        } else {
                            replaceKey = json.getString("key");
                            key = json.getString("key");
                        }
                    } else {
                        continue;
                    }
                } else {
                    replaceKey = marketId2Name.get(json.getLong("key"));
                    key = marketId2Name.get(json.getLong("key"));
                }
                JSONArray clue = json.getJSONObject("aggs011").getJSONArray("buckets");
                JSONArray customer = json.getJSONObject("aggs012").getJSONArray("buckets");
                JSONArray opportunity = json.getJSONObject("aggs013").getJSONArray("buckets");
                JSONArray contract = json.getJSONObject("aggs014").getJSONArray("buckets");
                // 线索
                Integer clueNum = 0;
                Integer invalidClue = 0;
                Integer conversionClue = 0;
                for (Object o1 : clue) {
                    if (o1!=null){
                        JSONObject json1 = (JSONObject) o1;
                        String key1 = json1.getString("key");
                        Integer num = json1.getJSONObject("deviceCard").getInteger("value");
                        clueNum+=num;
                        if (!Objects.equals(key1, ClueStatusEnum.INVALID.getCode())){
                            invalidClue+=num;
                        }
                        if (Objects.equals(key1, ClueStatusEnum.TRANSFORMED.getCode())){
                            conversionClue+=num;
                        }
                    }
                }
                // 客户
                Integer customerNum = 0;
                for (Object o2 : customer){
                    if (o2!=null){
                        JSONObject json2 = (JSONObject) o2;
                        Integer num2 = json2.getJSONObject("deviceCard").getInteger("value");
                        customerNum += num2;
                    }
                }
                Integer saleNum = 0;
                Integer saleWin = 0;
                BigDecimal saleMoney = new BigDecimal(0);
                BigDecimal winMoney = new BigDecimal(0);
                // 机会
                for (Object o3 : opportunity) {
                    if (o3 != null) {
                        JSONObject json3 = (JSONObject) o3;
                        String key3 = json3.getString("key");
                        saleMoney = json3.getJSONObject("saleMoney").getBigDecimal("value").add(saleMoney);
                        Integer integer = json3.getJSONObject("deviceCard").getInteger("value");
                        saleNum += integer;
                        // 【获取所有成功阶段的code，判断对应的key是否为成功阶段code】
                        if (winStatisticsCodeIn.contains(key3)) {
                            winMoney = winMoney.add(json3.getJSONObject("saleMoney").getBigDecimal("value"));
                            saleWin +=integer;
                        }
                    }
                }
                // 合同
                Integer contractNum = 0;
                BigDecimal contractMoney = new BigDecimal(0);
                // 机会
                for (Object o4 : contract) {
                    if (o4 != null) {
                        JSONObject json3 = (JSONObject) o4;
                        String key3 = json3.getString("key");
                        contractMoney = json3.getJSONObject("contractMoney").getBigDecimal("value").add(contractMoney);
                        Integer integer = json3.getJSONObject("deviceCard").getInteger("value");
                        contractNum += integer;
                    }
                }

                String attr;
                // 拼参数
                List<ResultDataTableVO> voList = new ArrayList<>();
                // 活动类型名称
                voList.add(new ResultDataTableVO(key, null));
                // 线索数量
                voList.add(new ResultDataTableVO(clueNum.toString(), createThroughDTO(chartResultPojo, replaceKey, "clueNum")));
                // 有效线索数量
                voList.add(new ResultDataTableVO(invalidClue.toString(), createThroughDTO(chartResultPojo, replaceKey, "clueInvalid")));
                // 已转化线索数量
                voList.add(new ResultDataTableVO(conversionClue.toString(), createThroughDTO(chartResultPojo, replaceKey, "conversionClue")));
                // 客户数
                voList.add(new ResultDataTableVO(customerNum.toString(), createThroughDTO(chartResultPojo,replaceKey, "customer")));
                //线索转客户转化率
                voList.add(new ResultDataTableVO(chartQueryHelp.getRate(clueNum, customerNum), null));
                // 销售机会数
                voList.add(new ResultDataTableVO(saleNum.toString(), createThroughDTO(chartResultPojo, replaceKey, "opportunityTotal")));
                //销售机会金额
                if (Objects.equals(saleNum, BasicConstant.ZERO)) {
                    voList.add(new ResultDataTableVO("-", null));
                } else {
                    voList.add(new ResultDataTableVO(String.valueOf(ChartResultUtil.formatVal4Num(saleMoney, numFormatEnum)), null));
                }
                // 线索转机会转化率
                voList.add(new ResultDataTableVO(chartQueryHelp.getRate(clueNum, saleNum), null));
                // 赢单机会数
                voList.add(new ResultDataTableVO(saleWin.toString(), createThroughDTO(chartResultPojo, replaceKey, "opportunityWin")));
                // 赢单机会金额
                if (Objects.equals(saleWin, BasicConstant.ZERO)) {
                    voList.add(new ResultDataTableVO("-", null));
                } else {
                    voList.add(new ResultDataTableVO(String.valueOf(ChartResultUtil.formatVal4Num(winMoney, numFormatEnum)), null));
                }
                // 合同订单数  透传
                voList.add(new ResultDataTableVO(contractNum.toString(), createThroughDTO(chartResultPojo,replaceKey, "contract")));
                // 合同订单金额
                if (Objects.equals(contractNum, BasicConstant.ZERO)) {
                    voList.add(new ResultDataTableVO("-", null));
                } else {
                    voList.add(new ResultDataTableVO(String.valueOf(Arith.div(contractMoney.doubleValue(),1,2)), null));
                }
                // 线索转合同订单转化率
                voList.add(new ResultDataTableVO(chartQueryHelp.getRate(clueNum,contractNum), null));

                tableData.add(voList);
            }
        }
        return tableData;
    }

    /**
     * 生成穿透实体类
     * @param chartResultPojo
     *      dictionaryCode 来标识: 市场id|对应跳转的值
     * @param key
     * @param num
     * @return
     */
    private String createThroughDTO(ChartResultPojo chartResultPojo, String key, String  num) {
        ThroughDTO throughDto = new ThroughDTO(chartResultPojo, chartResultPojo.getSystemCodeEnum());
        TimePojo timePojo = throughHelp.formatThroughTimeInfo(false, chartResultPojo.getFiscalYearTimePojo(), chartResultPojo.getStartTime(), chartResultPojo.getEndTime());
        throughDto.setDictionaryCodeThrough(key+"+"+num);

        return throughHelp.getThrough(throughDto, timePojo);
    }

    /**
     * 市场活动ROI
     * @param chartResultPojo
     * @param chartResultDetailVO
     * @return
     */
    private Object marketActivityROIChart(ChartResultPojo chartResultPojo, ChartResultDetailVO chartResultDetailVO) throws XbbException {
        ChartResultUtil.formatPage(chartResultPojo, PageConstant.DEFAULT_PAGE_SIZE_SMALL);
        String fieldTime = "marketEndTime";
        String corpid = chartResultPojo.getCorpid();
        String unit = chartResultPojo.getUnit();
        Integer numFormat = chartResultPojo.getNumFormat();
        NumFormatEnum numFormatEnum = NumFormatEnum.getByCode(numFormat);
        BoolQueryBuilder boolQueryBuilder  = chartQueryHelp.boolQueryBuilder4Time(chartResultPojo, fieldTime, true);
        // 子查询
        // 范围筛选
        Map<Long, String> marketId2Name = new HashMap<>(chartResultPojo.getPageSize());

        PageHelper pageHelper = chartQueryHelp.getMarketId(chartResultPojo, corpid, boolQueryBuilder,marketId2Name);
        // 时间筛选
        // 聚合查询对应的值
        TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("aggs01").field("marketId").order(BucketOrder.key(false));
        termsAggregationBuilder.subAggregation(new SumAggregationBuilder("actualCost").field("actualCost"));

        // 线索数量为0 展示为-
        TermsAggregationBuilder termsAggregationBuilder1 = AggregationBuilders.terms("aggs02").field("saleStage.keyword");
        // termsAggregationBuilder1.subAggregation(AggregationBuilders.topHits("marketId").explain(true).size(1).from(10).sort("marketId", SortOrder.ASC));
        CardinalityAggregationBuilder saleOpportunityIdCardinality = AggregationBuilders.cardinality("deviceCard").field("saleOpportunityId").precisionThreshold(10000);
        termsAggregationBuilder1.subAggregation(saleOpportunityIdCardinality);
        termsAggregationBuilder1.subAggregation(new SumAggregationBuilder("saleMoney").field("saleMoney"));
        termsAggregationBuilder.subAggregation(termsAggregationBuilder1);

        termsAggregationBuilder.size(Integer.MAX_VALUE);
        JSONObject resultJsonObject = esHelper.elasticAggs4Buckets2Object(IndexTypeEnum.IDX_STATICS_MARKET_DATA, boolQueryBuilder, termsAggregationBuilder);
        // 获取所有的成功阶段
        StageFindStrategy stageFindStrategy = StageFindFactory.getStageFindStrategy(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode());
        Set<String> winStatisticsCodeIn = stageFindStrategy.findStageCodeList(chartResultPojo.getCorpid(), new StageFindPojo(StageTypeEnum.getSuccessType()));
        JSONArray bucketsArray = resultJsonObject.getJSONArray("buckets");
        List<List<ResultDataTableVO>> tableData = new ArrayList<>();
        for (Object o : bucketsArray) {
            if (o != null){
                JSONObject json = (JSONObject) o;
                Long aLong = json.getLong("key");
                String key = marketId2Name.get(aLong);
                JSONArray winSaleOpportunitys = json.getJSONObject("aggs02").getJSONArray("buckets");
                Double actualCost = json.getJSONObject("actualCost").getDouble("value");
                Integer doc_count = json.getInteger("doc_count");
                if (!Objects.equals(doc_count, BasicConstant.ZERO)) {
                    actualCost/=doc_count;
                }
                BigDecimal bigDecimal = new BigDecimal(actualCost);
                // actualCost/
                Double saleMoney = 0.0;
                String  divide = null;
                Integer winNum = 0;
                for (Object o1 : winSaleOpportunitys) {
                    if (o1!= null){
                        JSONObject json1 = (JSONObject) o1;
                        Integer integer = json1.getJSONObject("deviceCard").getInteger("value");
                        // 【获取所有成功阶段的code，判断对应的key是否为成功阶段code】
                        if (winStatisticsCodeIn.contains(json1.getString("key"))) {
                            winNum+=integer;
                            saleMoney+= json1.getJSONObject("saleMoney").getDoubleValue("value");
                        }
                    }
                }
                if (Objects.equals(actualCost, 0.0 ) || Objects.equals(saleMoney, 0.0)) {
                    divide = "-";
                } else {
                    divide=Arith.div((saleMoney-actualCost)*100, actualCost, 2) +"%";
                }
                List<ResultDataTableVO> voList = new ArrayList<>();
                voList.add(new ResultDataTableVO(key, null));
                voList.add(new ResultDataTableVO(String.valueOf(ChartResultUtil.formatVal4Num(bigDecimal, numFormatEnum)), null));
                if (Objects.equals(winNum, BasicConstant.ZERO)) {
                    voList.add(new ResultDataTableVO("-", null));
                } else {
                    BigDecimal saleWinMoney = new BigDecimal(saleMoney);
                    voList.add(new ResultDataTableVO(String.valueOf(ChartResultUtil.formatVal4Num(saleWinMoney, numFormatEnum)), null));
                }
                voList.add(new ResultDataTableVO(divide, null));
                tableData.add(voList);
            }
        }
        ResultTableVO table = new ResultTableVO();
        table.setPageHelper(pageHelper);
        List<String> title = Arrays.asList(String.format(I18nMessageUtil.getMessage(ChartI18Constant.MARKET_ACTIVITY_ROI_TITLE), unit, unit).split(","));
        table.setTitle(systemChartHelp.titleNumRight(title));
        table.setMarketData(tableData);
        table.setTableName(SystemCodeEnum.MARKET_ACTIVITY_ROI_ACTIVITY.getName());
        table.setSystemCode(SystemCodeEnum.MARKET_ACTIVITY_ROI_ACTIVITY.getSystemCode());
        chartResultDetailVO.setTable(table);
        return chartResultDetailVO;
    }

    private Integer getRowCounts(BoolQueryBuilder boolQueryBuilder, String attr) throws XbbException {
        TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("aggs01").field(attr);
        CardinalityAggregationBuilder saleOpportunityIdCardinality = AggregationBuilders.cardinality("deviceCard").field(attr).precisionThreshold(10000);
        termsAggregationBuilder.subAggregation(saleOpportunityIdCardinality);
        JSONObject resultJsonObject = esHelper.elasticAggs4Buckets2Object(IndexTypeEnum.IDX_STATICS_MARKET_DATA, boolQueryBuilder, termsAggregationBuilder);
        JSONArray bucketsArray = resultJsonObject.getJSONArray("buckets");
        return bucketsArray.size();
    }

    @Override
    public Object getValueTarget(ChartResultPojo chartResultPojo) throws XbbException {
        return null;
    }

    @Override
    public Object customer(PanoramaPojo panoramaPojo) throws XbbException {
        return null;
    }
}
